import WebSocket from 'ws';
import InputStream from "./stream";
import {  ResponseOperate} from "./opearte";
import convert from "./packet/resp/resp.convert";
import eventBus from "./EventBus";
  class Server{
    ws:WebSocket
   async   init(){
        const ws = new WebSocket('ws://127.0.0.1:8888/ws');
        this.ws=ws;
       ws.binaryType = 'arraybuffer';



       ws.on('message', (data) => {
           console.log(data);

           const array=new Int8Array(data as ArrayBuffer);
           const stream=new InputStream(array);
           const type= stream.readInt() as ResponseOperate;
           let message = convert(type,stream);
           // console.info(message)
           eventBus.emit(type,message)





       });


       ws.on('close', () => {
           console.log('Disconnected from WebSocket server');
       });
        return new Promise<void>((resolve, reject)=>{
            ws.on('open', () => {

                resolve()


            });
        })



    }
    send(data:Int8Array){
        this.ws.send(data);
    }
}
export const  server=new Server();


